package com.ts.utils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 通过jackson进行json与bean转换的工具类
 * @author JeffCao
 *
 */
public class JacksonJsonUtil {
	private static JacksonJsonUtil util = null;
	private static Object object = new Object();
	private ObjectMapper mapper = null;
	
	public static JacksonJsonUtil getInstance(){
		if(util == null){
			synchronized (object) {
				util = new JacksonJsonUtil();
			}
		}
		return util;
	}
	
	private JacksonJsonUtil(){
		mapper = new ObjectMapper();
		//防止json串中存在不需要的字段时，反序列化出错。
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setSerializationInclusion(Include.NON_NULL);
	}
    /**
     * 将Bean转换成JSON字符串
     * @param obj
     * @return
     * @throws Exception
     */
    public String beanToJson(Object obj) throws Exception{
    	return mapper.writeValueAsString(obj);
    }
    /**
     * 将JSON转成JAVA对象
     * @param json
     * @param cls
     * @return
     * @throws Exception
     */
    public Object jsonToBean(String json, Class cls) throws Exception{
    	return mapper.readValue(json, cls);
    }
    public static void main(String args[]){
    	try {
    		LinkedHashMap map = (LinkedHashMap) JacksonJsonUtil.getInstance().jsonToBean("{\"message\":\"request error\",\"code\":-1,\"data\":[{\"icd10_code\":\"A01.1\",\"icd10_name\":\"A01.1\"},{\"icd10_code\":\"A02.1\",\"icd10_name\":\"A01.1\"}]}", Map.class);
    		int code = (int) map.get("code");
    		System.out.println(((LinkedHashMap)(((List)map.get("data")).get(0))).get("icd10_code"));
//			System.out.println(list.get(0).get("icd10_code"));
//			LinkedHashMap map = (LinkedHashMap) JacksonJsonUtil.getInstance().jsonToBean("{\"icd10_code\":\"A01.1\",\"apply\":{\"name\":\"hello\"}}", Map.class);
//			System.out.println(((LinkedHashMap)map.get("apply")).get("name"));
    		System.out.println("");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
